package com.qf.sclg.exception;

import com.alibaba.fastjson.JSONObject;
import com.qf.sclg.result.ResponseCode;
import com.qf.sclg.result.ResponseData;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

/**
 * 全局异常工具类的封装
 * Created with IntelliJ IDEA.
 * User: zdk
 * Date: 2021/10/14 10:31
 * Description:
 * Version: V1.0
 */
//加载GlobalException类
@Component
public class GlobalException implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
//返回json对象
//        JSONObject jsonObject = new JSONObject();
        ResponseData responseData = new ResponseData();
        if(ex instanceof BusinessException){
            BusinessException e = (BusinessException) ex;
//            把code和info返回给前端
//            String code = e.getCode();
//            String message =e.getInfo();
            responseData.setCode(e.getCode());
            responseData.setMessage(e.getMessage());
        }else if (ex instanceof SQLException){
//            sql异常，返回sql状态码和消息
//            String code = ResponseCode.SQLEXCEPTION.getCode();
//            String message = ResponseCode.SQLEXCEPTION.getMessage();
            responseData.setCode(ResponseCode.SQLEXCEPTION.getCode());
            responseData.setMessage(ResponseCode.SQLEXCEPTION.getMessage());
        }else {
            responseData.setCode(ResponseCode.ERROR.getCode());
            responseData.setMessage(ResponseCode.ERROR.getMessage());

        }

//使用response响应，返回
        try {
            String s = JSONObject.toJSONString(responseData);
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().write(s);
//            刷新并关闭
            response.getWriter().flush();
            response.getWriter().close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
